package com.starsea.book.ui.newpage.viewmodel

import android.app.Application
import android.content.Context
import android.os.CountDownTimer
import androidx.lifecycle.MutableLiveData
import com.google.gson.JsonParser
import com.starsea.book.base.BaseViewModel
import com.starsea.book.constant.AppConst
import com.starsea.book.constant.PreferKey
import com.starsea.book.help.http.newCallResponseBody
import com.starsea.book.help.http.okHttpClient
import com.starsea.book.help.http.text
import com.starsea.book.ui.main.MainActivity
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.LoginInfoEntity
import com.starsea.book.ui.newpage.utils.CountTimeState
import com.starsea.book.ui.newpage.utils.gsonNormal
import com.starsea.book.utils.LogUtils
import com.starsea.book.utils.putPrefBoolean
import com.starsea.book.utils.putPrefString
import com.starsea.book.utils.startActivity
import com.starsea.book.utils.toastOnUi
import okhttp3.RequestBody.Companion.toRequestBody

class LoginViewModel(application: Application) : BaseViewModel(application) {

    val codeResult = MutableLiveData<Int>()

    var countTime = MutableLiveData<CountTimeState<Int>>()

    val loginResutl = MutableLiveData<BaseEntity<String>>()
    val registerResutl = MutableLiveData<BaseEntity<String>>()


    fun getCode(phone: String) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/common/sendSmsCode?phone=${phone}"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(">>> ", "it = " + it)
                val objects = JsonParser.parseString(it).asJsonObject
                val status = objects.get("status").asInt
                val msg = objects.get("msg").asString
                if (status == 200) {
                    codeResult.postValue(status)
                } else {
                    errorResult.postValue(msg)
                    context.toastOnUi(msg)
                }

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun login(phone: String, code: String, mContext: Context) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/login/loginByPhone?phone=${phone}&code=${code}"))
                    .post("".toRequestBody())

            }.text().let {
                LogUtils.e(">>>> ", "it = " + it)

                val entity: BaseEntity<LoginInfoEntity> =
                    it.gsonNormal(LoginInfoEntity::class.java)
                if (entity.status == 200) {
                    mContext.putPrefBoolean(PreferKey.isLogin, true)
                    mContext.putPrefString(PreferKey.token, entity.data!!.token ?: "")
                    mContext.startActivity<MainActivity>()
                } else {
                    errorResult.postValue(entity.msg)
                }
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun register(
        phone: String,
        password: String,
        code: String,
        invitationCode: String,
        mContext: Context
    ) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/customer/register?phone=${phone}&code=${code}&password=${password}&invitationCode=${invitationCode}"))
                    .post("".toRequestBody())

            }.text().let {
                LogUtils.e(">>>> ", "it = " + it)

                val entity: BaseEntity<String> =
                    it.gsonNormal(String::class.java)
                if (entity.status == 200) {
//                    mContext.putPrefBoolean(PreferKey.isLogin, true)
//                    mContext.putPrefString(PreferKey.token, entity.data ?: "")
//                    mContext.startActivity<MainActivity>()
                    registerResutl.postValue(entity)
                } else {
                    errorResult.postValue(entity.msg)
                    context.toastOnUi(entity.msg)
                }
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun category(type: Int) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/book_type_all?type=${type}"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(">>>> ", "it = " + it)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun count() {
        var con = object : CountDownTimer(60 * 1000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
                (millisUntilFinished / 1000).also {
                    countTime.value = CountTimeState.onCountLoading(it.toInt())
                }
            }

            override fun onFinish() {
                countTime.value = CountTimeState.onCountFinish(0)
            }
        }.start()
    }
}